import requests
import json
import base64
import socket
import numpy as np
import cv2


def getByte(path):
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read())
    img_str = img_byte.decode('ascii')
    return img_str



def getIP():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('127.0.0.1', 8080))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


def predict_garbage():
    img_str = getByte('./garbage_img/garbage.jpg')
    url = 'http://' + str(getIP()) + ':8080/predict'
    data = {'img': img_str, 'type': '0', 'useAntiSpoofing': '0'}
    json_mod = json.dumps(data)     # 将python对象编码为json
    res = requests.post(url=url, data=json_mod)
    res = eval(res.text)
    result = res.split('/', 1)
    return result[1]


